﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tools;

namespace test_2025_4_12
{
    public partial class FrmSerialPort : Form
    {
        private FR102 _fr102 = new FR102();
        public FrmSerialPort()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void FrmSerialPort_Load(object sender, EventArgs e)
        {
            RefreshCom();
        }

        private void RefreshCom()
        {
            cmbPortNum.Items.Clear();

            String[] strPortNum = System.IO.Ports.SerialPort.GetPortNames();

            if (strPortNum.Length > 0) {

                for(int i  = 0; i < strPortNum.Length; i++)
                {
                    if (strPortNum[i].Length < 7)
                    {
                        cmbPortNum.Items.Add(strPortNum[i]); 
                    }
                }

                cmbPortNum.SelectedIndex = 0;
               // MessageBox.Show("没有检查到串口，请检查串口是否与电脑正常连接！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            }
            else
            {
                MessageBox.Show("没有检查到串口，请检查串口是否与电脑正常连接！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnOpenPort_Click(object sender, EventArgs e)
        {
            btnOpenPort.Enabled = false;
            if (cmbPortNum.Text != "")
            {
               if(_fr102.OpenSerialPort(cmbPortNum.Text.Trim()) == 0x00)
                {
                    MessageBox.Show(String.Format("打开串口：串口{0}打开成功！", cmbPortNum.Text.Trim()),
                            "提示",MessageBoxButtons.OK, MessageBoxIcon.Warning );
                }
               else
                {
                    MessageBox.Show(String.Format("打开串口：串口打卡失败！\n请检查串口{0}是否被其他程序占用！", cmbPortNum.Text.Trim()), "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
        }

        private void btnClosePort_Click(object sender, EventArgs e)
        {
            
                if (_fr102.CloseSerialPort() == 0x00)
                {
                    MessageBox.Show(String.Format("关闭串口：串口{0}关闭成功！", cmbPortNum.Text.Trim()),
                            "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    cmbPortNum.Enabled = true;
                    btnOpenPort.Enabled = true;
                    btnOpenPort.Enabled = true;
                }
                else
                {
                    MessageBox.Show(String.Format("关闭串口：串口{0}关闭失败！", cmbPortNum.Text.Trim()), "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            
        }
    }
}
